package com.beyondsoft.mcms.common;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.beyondsoft.mcms.domain.Fee;
import com.beyondsoft.mcms.domain.FeeAmount;
import com.beyondsoft.mcms.domain.Item;
import com.beyondsoft.mcms.domain.MemberInfo;

public class CommonServiceImpl  {

	@Autowired
	JavaMailSenderImpl mailSender;
	@Autowired
	SimpleMailMessage mailMessage;
	
	public void generateByFeeAmount() {
        Calendar c = Calendar.getInstance();
        if (1 != c.get(Calendar.DAY_OF_MONTH)) {
            return;
        }
        
        List<Fee> fees = new ArrayList<Fee>();
        List<FeeAmount> feeAmounts = FeeAmount.findAllFeeAmounts();
        List<MemberInfo> memberInfos = MemberInfo.findAllMemberInfoes();
        for (int i = 0; i < feeAmounts.size(); i++) {
            FeeAmount feeConfig = feeAmounts.get(i);
            
            BigDecimal amount = feeConfig.getPayAmount();
            if (amount.compareTo(new BigDecimal(0.0)) == 0){continue;}
            
            Item feePeriod = feeConfig.getFeePeriod();
            List<Date> periodList = getPeriod(feePeriod);
            if (periodList.size() == 0) {continue; }
            
            Item businessType = feeConfig.getBusinessType();
            Item positionType = feeConfig.getPositionType();
            
            for (Iterator<MemberInfo> it = memberInfos.iterator(); it.hasNext(); ) {
                MemberInfo memberInfo = it.next();
                if (memberInfo.getBusinessType().getId().equals(businessType.getId()) 
                		&& memberInfo.getPositionType().getId().equals(positionType.getId())) {
                    Fee fee = new Fee();
                    fee.setAmountToPay(amount);
                    fee.setCreateDate(new Date());
                    fee.setCreatedBy("System");
                    fee.setPayer(memberInfo);
                    fee.setPayStatus(Item.findItem(Constants.PAY_STATUS_NOTPAID));
                    fee.setPeriodStartDate(periodList.get(0));
                    fee.setPeriodEndDate(periodList.get(1));
                    //fees.add(fee);
                    fee.persist();
                }
            }
        }
    }

    private List<Date> getPeriod(Item feePeriod) {
        List<Date> datePeriod = new ArrayList<Date>();
        Calendar c = Calendar.getInstance();
        if (1 != c.get(Calendar.DAY_OF_MONTH)) {
            return datePeriod;
        }
        if (feePeriod.getId().equals(Constants.FEE_PERIOD_YEAR)) {
            if (c.get(Calendar.MONTH) == 0) {
                datePeriod.add(new Date());
                int year = c.get(Calendar.YEAR);
                c.set(year, 11, 31);
                datePeriod.add(c.getTime());
            }
        } else if (feePeriod.getId().equals(Constants.FEE_PERIOD_HALFYEAR)) {
            if (c.get(Calendar.MONTH) == 0 || c.get(Calendar.MONTH) == 6) {
                datePeriod.add(new Date());
                int year = c.get(Calendar.YEAR);
                if (c.get(Calendar.MONTH) == 0) {
                    c.set(year, 5, 30);
                } else if (c.get(Calendar.MONTH) == 6) {
                    c.set(year, 11, 31);
                }
                datePeriod.add(c.getTime());
            }
        } else if (feePeriod.getId().equals(Constants.FEE_PERIOD_QUARTER)) {
            if (c.get(Calendar.MONTH) == 0 || c.get(Calendar.MONTH) == 3 
            		|| c.get(Calendar.MONTH) == 6 || c.get(Calendar.MONTH) == 9) {
                datePeriod.add(new Date());
                int year = c.get(Calendar.YEAR);
                if (c.get(Calendar.MONTH) == 0) {
                    c.set(year, 2, 31);
                } else if (c.get(Calendar.MONTH) == 3) {
                    c.set(year, 5, 30);
                } else if (c.get(Calendar.MONTH) == 6) {
                    c.set(year, 8, 30);
                } else if (c.get(Calendar.MONTH) == 9) {
                    c.set(year, 11, 31);
                }
                datePeriod.add(c.getTime());
            }
        } else if (feePeriod.getId().equals(Constants.FEE_PERIOD_MONTH)) {
            datePeriod.add(new Date());
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            c.set(year, month + 1, 1);
            c.add(Calendar.DAY_OF_YEAR, -1);
            datePeriod.add(c.getTime());
        }
        return datePeriod;
    }
    
    public List<Date> getPeriodLately(Item feePeriod) {
        List<Date> datePeriod = new ArrayList<Date>();
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        
        if (feePeriod.getId().equals(Constants.FEE_PERIOD_YEAR)) {
        	
            c.set(year, 0, 1);
            datePeriod.add(c.getTime());
            c.set(year, 11, 31);
            datePeriod.add(c.getTime());
            
        } else if (feePeriod.getId().equals(Constants.FEE_PERIOD_HALFYEAR)) {
            
            if (c.get(Calendar.MONTH) < 6) {
            	c.set(year, 0, 1);
                datePeriod.add(c.getTime());
                c.set(year, 5, 30);
                datePeriod.add(c.getTime());
                
            } else {
            	c.set(year, 6, 1);
                datePeriod.add(c.getTime());
                c.set(year, 11, 31);
                datePeriod.add(c.getTime());
            }
            
        } else if (feePeriod.getId().equals(Constants.FEE_PERIOD_QUARTER)) {
                if (c.get(Calendar.MONTH) < 3) {
                	c.set(year, 0, 1);
                    datePeriod.add(c.getTime());
                    c.set(year, 2, 31);
                    datePeriod.add(c.getTime());
                    
                } else if (c.get(Calendar.MONTH) < 6) {
                	c.set(year, 3, 1);
                    datePeriod.add(c.getTime());
                    c.set(year, 5, 30);
                    datePeriod.add(c.getTime());
                    
                } else if (c.get(Calendar.MONTH) < 9) {
                	c.set(year, 6, 1);
                    datePeriod.add(c.getTime());
                    c.set(year, 8, 30);
                    datePeriod.add(c.getTime());
                    
                } else {
                	c.set(year, 9, 1);
                    datePeriod.add(c.getTime());
                    c.set(year, 11, 31);
                    datePeriod.add(c.getTime());
                }
        
        } else if (feePeriod.getId().equals(Constants.FEE_PERIOD_MONTH)) {
        	int month = c.get(Calendar.MONTH);
            
        	c.set(year, month, 1);
        	datePeriod.add(c.getTime());
            
        	c.set(year, month + 1, 1);
            c.add(Calendar.DAY_OF_YEAR, -1);
            datePeriod.add(c.getTime());
        }
        return datePeriod;
    }
    
    public void msgNotice(){
    	
    	List<Fee> feeList = Fee.findFeesByPayerAndPayStatus(null, Item.findItem(Constants.PAY_STATUS_NOTPAID)).getResultList();
    	sendNotice(feeList);
    	
    }
    
    public void sendNotice(List<Fee> feeList){
    	for (Iterator<Fee> it=feeList.iterator(); it.hasNext(); ){
    		Fee fee = it.next();
    		MemberInfo memberInfo = fee.getPayer();
    		String delegateEmail = memberInfo.getDelegateEmail();
			String contactEmail = memberInfo.getContactEmail();
			
			List<String> mailTo = new ArrayList<String>();
	    	mailTo.add(delegateEmail);
			if(contactEmail!=null && contactEmail.length()>0){
				mailTo.add(contactEmail);
			}
			mailTo.add("csj_88@126.com");
			String[] to = new String[mailTo.size()];

			try {
				MimeMessage mimeMessage = mailSender.createMimeMessage();
				MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
				messageHelper.setFrom(mailMessage.getFrom());
				//messageHelper.setBcc(mailTo.toArray(to));
				messageHelper.setTo(mailTo.toArray(to));
				messageHelper.setSubject("金融行业协会缴纳会员管理费的通知");
				String content = "<br/><br/>缴费期间：" + fee.getPeriodStartDate()+"--"+fee.getPeriodEndDate() 
						+ "<br/><br/>缴费金额：" + fee.getAmountToPay().doubleValue()
						+ "<br/><br/>服务人员：" 
						+ "<br/><br/>服务电话：" ;
				messageHelper.setText(content, true);
				mailSender.send(mimeMessage);
				System.out.println("邮件成功发送至:" + memberInfo.getMemberName());

			} catch (Exception me) {
				System.out.println("邮件发送给" + memberInfo.getMemberName() +"失败！ 原因："+ me.getMessage());
				continue;
			}
    	}
    	
    	for (Iterator<Fee> it=feeList.iterator(); it.hasNext(); ){
    		Fee fee = it.next();
    		MemberInfo memberInfo = fee.getPayer();
    		String delegateMobile = memberInfo.getDelegateMobile();
    		String contactMobile = memberInfo.getContactMobile();
    		
    		List<String> smsTo = new ArrayList<String>();
        	smsTo.add(delegateMobile);
    		if (contactMobile!=null && contactMobile.length()>0){
    			smsTo.add(contactMobile);
    		}
    		
    		try{
	    		Map<String, String> returnMsg = UmsApiServiceImpl.sendShortMsgByPost("金融行业协会缴纳会员管理费的通知： " 
	        			+ "缴费期间：" + fee.getPeriodStartDate()+"--"+fee.getPeriodEndDate() 
	        			+ "缴费金额：" + fee.getAmountToPay().doubleValue()
	        			+ "服务电话：" ,
	        			smsTo.toString());
	    		
	    		System.out.println("短信成功发送至:" + memberInfo.getMemberName());
	    		
    		}catch (Exception me) {
				System.out.println("短信发送给" + memberInfo.getMemberName() +"失败！ 原因："+ me.getMessage());
				continue;
			}
    	}
    	
    	
    	
    }

}
